﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Business.Common;
using NetDon.OA.Data.EntityClasses;
using NetDon.OA.Interface;
using NetDon.OA.Interface.CRM;
using NetDon.OA.Portal.Common;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.OA.Portal.Shunting
{
    [Navigation("干线流程", "出单信息管理")]
    [Function("eLogistics.IssuingOrderInfoManagement")]
    public partial class IssuingOrderInfoManagement : PageBase
    {
        protected int? CurrentOrderStatus { get; set; }


        protected void Page_Load(object sender, EventArgs e)
        {
            btnBatchEdit.Attributes.Add("onclick", "batchModifyOrder('{0}');return false;".Formato(this.gridOrderList.ClientID));
            if (!IsPostBack)
            {
                PageQueryAdapter1.PageSize = 20;
                txtReceivingOrderDateStart.Text = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                txtReceivingOrderDateEnd.Text = DateTime.Now.ToString("yyyy-MM-dd");
                this.ddlCustomer.InsertEmptyItem(ListEmptyType.Select);
                ddlCompany.InsertEmptyItem(ListEmptyType.Select);
                if (!this.IsSuperRoles())
                {
                    ddlCompany.SelectedValue = CurrentApplicationContext.CompanyId.ToString();
                    ddlCompany.Enabled = false;
                }
                PageQueryAdapter1.PerformQuery();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.PerformQuery();
        }



        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ObjectDataSourceCustomers.Selecting += (ds, dsArgs) =>
                {
                    dsArgs.InputParameters["areaId"] = CurrentApplicationContext.CompanyId.ToString();
                };


        }
        public void ddlCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(ddlCustomer.SelectedValue))
            {

                LoadGoodsShippedTypes(ddlCustomer.SelectedValue.ToGuid());
            }


        }


        private void LoadGoodsShippedTypes(Guid customerId)
        {
            this.ddlGoodsShippedTypeId.Items.Clear();
            this.ddlGoodsShippedTypeId.DataSource = ServiceContainer.GetService<ICustomerInfoService>().GetCustomerGoodsShippTypes(
               customerId, CurrentApplicationContext.CompanyId);
            this.ddlGoodsShippedTypeId.DataBind();
            ddlGoodsShippedTypeId.InsertEmptyItem(ListEmptyType.Select);
        }

        protected void PageQueryAdapter1_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {

            var service = ServiceContainer.GetService<IIssuingOrderService>();
            var s = service.SearchOrdersByCondition((IssuingOrderSearchCriteria)e.Condition,
                                                    gridOrderList.SortExpression,
                                                    gridOrderList.SortDirection, e.PageSize, e.PageIndex);
            e.DataSource = s;

        }

        protected void PageQueryAdapter1_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            var service = ServiceContainer.GetService<IIssuingOrderService>();
            e.RecordCount = service.GetOrderCount((IssuingOrderSearchCriteria)e.Condition) ;
        }

        protected void PageQueryAdapter1_PerformGetCondition(object sender, PerformGetConditionEventArgs e)
        {


            var criteria = new IssuingOrderSearchCriteria
            {
                
             
            };

            if (!MiscUtilities.IsNullOrEmpty(ddlCompany.SelectedValue))
            {
                criteria.AreaId = ddlCompany.SelectedValue.ToGuid();
            }

              
            DateTime? dateStart = null, dateEnd = null;
            if (!string.IsNullOrEmpty(txtReceivingOrderDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtReceivingOrderDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtReceivingOrderDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtReceivingOrderDateEnd.Text.Trim());
            }
            if (dateStart.HasValue || dateEnd.HasValue)
            {
                criteria.ReceivingOrderDate = new Range<DateTime?>(dateStart, dateEnd);
            }
            if (!string.IsNullOrEmpty(txtOrderCode.Text.Trim()))
            {
                criteria.OrderCode = txtOrderCode.Text.Trim();
            }
            if (!string.IsNullOrEmpty(ddlProvince.SelectedValue))
            {
                criteria.DeliveryProvince = ddlProvince.SelectedValue;
            }
            if (!string.IsNullOrEmpty(ddlCity.SelectedValue))
            {
                criteria.DeliveryCity = ddlCity.SelectedValue;
            }
            if (!string.IsNullOrEmpty(txtOrderDeliveryCode.Text.Trim()))
            {
                criteria.DeliveryOrderCode = txtOrderDeliveryCode.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtTransportationPlanCode.Text.Trim()))
            {
                criteria.TransportationPlanCode = txtTransportationPlanCode.Text.Trim();
            }

            //if (!string.IsNullOrEmpty(ddlPaymentMethod.SelectedValue))
            //{
            //    criteria.PaymentMethod = ddlPaymentMethod.SelectedValue.ToGuid();
            //}
            //if (!string.IsNullOrEmpty(ddlEntruckingAddress.SelectedValue))
            //{
            //    criteria.EntruckingAddress = ddlEntruckingAddress.SelectedValue.ToGuid();
            //}
            if (!string.IsNullOrEmpty(ddlCheckoutType.SelectedValue))
            {
                criteria.CheckoutType = (int)EnumUtilities.Parse<CheckoutType>(ddlCheckoutType.SelectedValue); ;
            }
            if (!MiscUtilities.IsNullOrEmpty(ddlRouteTypeId.SelectedValue.ToGuid()))
            {
                criteria.RouteTypeId = ddlRouteTypeId.SelectedValue.ToGuid();
            }
            if (!string.IsNullOrEmpty(ddlGoodsShippedTypeId.SelectedValue))
            {
                criteria.GoodsShippedTypeId = ddlGoodsShippedTypeId.SelectedValue.ToGuid();
            }

            if (!MiscUtilities.IsNullOrEmpty(ddlCustomer.SelectedValue.ToGuid()))
            {
                criteria.CustomerId = ddlCustomer.SelectedValue.ToGuid();
            }
            var context = (CurrentApplicationContext);
            if (context.BusinessType != BusinessType.All)
            {
                criteria.BusinessType = (int)context.BusinessType;
            }
         
            if (!string.IsNullOrWhiteSpace(ddlIssuingOrderStatus.SelectedValue))
            {
                criteria.OrderStatus = (int)ddlIssuingOrderStatus.SelectedValue.ToEnum<OrderStatus>();
            }


            e.Condition = criteria;
        }

        protected void btnReload_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.ReloadCurrentPage();
        }

        protected void gridOrderList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);

                var orderId = e.Row.Attributes["Id"] = Convert.ToString(DataBinder.Eval(entity, "Id"));


                var btnEdit = (ImageButton)e.Row.FindControl("btnEdit");
                if (btnEdit != null)
                {
                    btnEdit.OnClientClick = string.Format("modifyOrder('{0}');return false;", orderId);
                }

                var btnDetails = (ImageButton)e.Row.FindControl("btnDetails");
                if (btnDetails != null)
                {
                    btnDetails.OnClientClick = string.Format("modifyOrder('{0}');return false;", orderId);
                }

                var btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
                if (btnDelete != null)
                {
                    btnDelete.OnClientClick = string.Format("deleteOrder('{0}');return false;", orderId);
                    btnDelete.Visible = IsManager();

                }
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            var orderId = fieldOrderId.Value.ToGuid();
            var service = ServiceContainer.GetService<IIssuingOrderService>();
            //var order = service.GetSimpleIssuingOrder(orderId);
            //if ((int)order.OrderStatus >= (int)OrderStatus.Entrucked)
            //{
                //if (order.OrderStatus == OrderStatus.Entrucked)
                //{
                //    Alert("该订单不可以删除！（原因：已经装车并发出。）");
                //}
                //else if (order.OrderStatus == OrderStatus.OnWayTrackCompleted)
                //{
                //    Alert("该订单不可以删除！（原因：已经完成在途跟踪。）");
                //}
                //else if (order.OrderStatus == OrderStatus.ReceiptTrackComplted)
                //{
                //    Alert("该订单不可以删除！（原因：已经完成回单跟踪。）");
                //}
                //else if (order.OrderStatus == OrderStatus.Closed)
                //{
                //    Alert("该订单不可以删除！（原因：已经结案。）");
                //}
                //return;
            //}
            if (ServiceContainer.GetService<IRevenueMachineAccountService>().IsRevenueMachineAccountInvoiceExists(orderId))
            {
                Alert("该订单不可以删除！（原因：已经开票。）");
            }
            if (service.RemoveOrder(orderId))
            {
                PageQueryAdapter1.ReloadCurrentPage();
                Alert("删除成功!");
            }
        }



        protected string GetCityName(object issuingOrderId)
        {
            if (MiscUtilities.IsNullOrEmpty(issuingOrderId)) return string.Empty;
            var orderService = ServiceContainer.GetService<IIssuingOrderService>();
            var issuingOrderDeliveryData = orderService.GetIssuingOrderDeliveryByOrderId(issuingOrderId.ToString().ToGuid());
            if(!issuingOrderDeliveryData.Any()) return string.Empty;
            return issuingOrderDeliveryData.Select(a => a.DeliveryCity).Distinct().Select(a => new CityEntity(a).Name).Aggregate((a, b) => a + "," + b);

        }

    }
}